<?php
require_once(dirname(__FILE__).'/Alipay/AopClient.php');
/**
 * @name Alipay AopClient
 */

class AlipayAop
{
    #应用公钥
    const PARTNER_PUBLIC_KEY = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqnj35QHIhvQBqaFipf7UbsZ+JyIKdC/YgkYjNhdIU/yfCa9U7tryuABf6Bb4IGa5N255L49Kp1VXF0a70Eu95r0XXL9f/4dYaFdl+7qg+sQwHEJv8X/5rgUKJjhL6dyki/CZXYa8M5RGG9C2GKRpCXHoQFQGV9d3Fc6gVgmZocpDxfZHEthoJBxs/WED64S9okpVlKTSE1wihnt3B1yot4yvOMmBG++TCR5BGEvaHLO+46sGNutP9kC8dZaZ38qxieSBXYP31rFar577pa2eeYN0DI1MGPrC4fB2SwYQzlhTMSfj1qLlPRjPIP/9Px+ON8rmIJDJbdqaxxrSe0D+GQIDAQAB';
    #应用私钥
    const PARTNER_PRIVATE_KEY = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCqePflAciG9AGpoWKl/tRuxn4nIgp0L9iCRiM2F0hT/J8Jr1Tu2vK4AF/oFvggZrk3bnkvj0qnVVcXRrvQS73mvRdcv1//h1hoV2X7uqD6xDAcQm/xf/muBQomOEvp3KSL8JldhrwzlEYb0LYYpGkJcehAVAZX13cVzqBWCZmhykPF9kcS2GgkHGz9YQPrhL2iSlWUpNITXCKGe3cHXKi3jK84yYEb75MJHkEYS9ocs77jqwY260/2QLx1lpnfyrGJ5IFdg/fWsVqvnvulrZ55g3QMjUwY+sLh8HZLBhDOWFMxJ+PWouU9GM8g//0/H443yuYgkMlt2prHGtJ7QP4ZAgMBAAECggEAaP+lQEp+5pB4TbD3f+KbmbdskFHpOnMV2fe1TGW+yOw6UM7Lc2ssQKUKbXtoTRy4TCohPmf1xWdNAyswFzXvu6UQNLIzQMJuc6YRTKFA8fPQ5jcNmCQI92RnQe8+4sZiG0eQTwjj9qkHHa7J2he6EnU0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
    const ALIPAY_PUBLIC_KEY = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzw1g2jIAxY1Hs9JBBalhOTAW1pC1gD205G38HE3hl395u0vV+f+k9QzRE14XVNhj23uZhnHDBieWp6K/8nQJmnNOurP/0ExMm6MFWiVRKeW15DkvV/CEhz9qDwvv7/aZnUUIGGbHqttbLjrFrIkVdIM0JfMBmc2QqM/UkCTDlkdPr84JqNf2HO+ilR/ty/8i7y6o3UjL3gzZH1HKz/H8WRISIazplFsqjCMcntTIyYkNGno7DJk1/bvq/9QwyCRJCC9eRqaNvHnONV14Wr8yOKqKLHo2rtywAMq9zbn3BcrhWrGZvGxfKv5Xh9VCkFwto2lby7wG2gwAAzCFvWTp0QIDAQAB';
    #app id
    const APPID = '2018070360519254';

    const GATEWAY_URL = 'https://openapi.alipay.com/gateway.do';

    const FORMAT = 'json';

    const POST_CHARSET = 'UTF-8';

    const SIGN_TYPE = 'RSA2';

    const API_VERSION = '1.0';

    #收款方账户类型 payee_type
    # 1、ALIPAY_USERID：支付宝账号对应的支付宝唯一用户号。以2088开头的16位纯数字组成。
    #2、ALIPAY_LOGONID：支付宝登录号，支持邮箱和手机号格式。
    const ALIPAY_PAYFEE_TYPE = 'ALIPAY_LOGONID';
    #付款方姓名
    const PAYER_SHOW_NAME = '头号试玩平台';

    public function __construct()
    {

    }


    /**
     * 单笔转账到支付宝账户
     * @param out_biz_no:商户转账唯一订单号
     * @param payee_account : 收款方账户。与payee_type配合使用。付款方和收款方不能是同一个账户。
     * @param amount:转账金额，单位：元。
     * @param payer_show_name :付款方姓名
     * @param payee_real_name :收款方真实姓名
     * @param remark :转账备注
     * @return array order_id:支付宝转账单据号
     * @return array pay_date:支付时间：格式为yyyy-MM-dd HH:mm:ss，仅转账成功返回。
     */
    public function TransToaccount($out_biz_no, $payee_account, $payee_real_name, $amount)
    {
        $ret = array(
            'errcode' => 1,
            'errmsg' => '',
            'errmsg_alipay' => '',
            'order_id' => '',
            'pay_date' => ''
        );
        if(empty($out_biz_no) || empty($payee_account) || empty($payee_real_name) || empty($amount)) {
            $ret['errcode'] = 1;
            $ret['errmsg'] = '参数错误';
            return $ret;
        }
        $aop = new AopClient ();
        $aop->gatewayUrl = self::GATEWAY_URL;
        $aop->appId = self::APPID;
        $aop->rsaPrivateKey = self::PARTNER_PRIVATE_KEY;
        $aop->alipayrsaPublicKey= self::ALIPAY_PUBLIC_KEY;
        $aop->apiVersion = self::API_VERSION;
        $aop->signType =  self::SIGN_TYPE;
        $aop->postCharset = self::POST_CHARSET;
        $aop->format = self::FORMAT;

        require_once(dirname(__FILE__).'/Alipay/request/AlipayFundTransToaccountTransferRequest.php');
        $request = new AlipayFundTransToaccountTransferRequest ();
        $curtime = time();
        $bizContent = array(
            "out_biz_no" => $out_biz_no,
            "payee_type" => self::ALIPAY_PAYFEE_TYPE,
            "payee_account" => $payee_account,
            "amount" => $amount,
            "payer_show_name" => self::PAYER_SHOW_NAME,
            "payee_real_name" => $payee_real_name,
            "remark" => "头号试玩平台结算",
        );
        $request->setBizContent(json_encode($bizContent));
        $result = $aop->execute ( $request);

        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode) ) {
            if($resultCode == 10000) {
                $ret['errcode'] = 2;
                $ret['errmsg'] = '成功';
                $ret['order_id'] = $result->$responseNode->order_id;
                $ret['pay_date'] = $result->$responseNode->pay_date;
            } else {
                $sub_code = $result->$responseNode->sub_code;
                $sub_msg = $result->$responseNode->sub_msg;

                #记录alipay_error
                $alpay_error_model = new AlipayErrorModel();
                $add_alipay_error = array(
                    'out_biz_no' => $out_biz_no,
                    'err_code' => $resultCode,
                    'sub_code' => $sub_code,
                    'err_msg' => $sub_msg,
                    'created_at' => $curtime,
                );
                $alpay_error_model->addData($add_alipay_error);

                $ret['errcode'] = 1;
                $ret['errmsg'] = $sub_msg;

                if($sub_code == 'SYSTEM_ERROR') {
                    self::TransToaccount($out_biz_no, $payee_account, $payee_real_name, $amount);
                }
                /*switch ($sub_code){
                    case 'INVALID_PARAMETER':
                        $ret['errmsg'] = '参数错误！';
                        break;
                    case 'SYSTEM_ERROR':
                        self::TransToaccount($out_biz_no, $payee_account, $payee_real_name, $amount);
                        $ret['errmsg'] = '支付宝系统繁忙，请稍候再试！';
                        break;
                    case 'PERMIT_CHECK_PERM_LIMITED':
                    case 'PERM_AML_NOT_REALNAME_REV':
                    case 'EXCEED_LIMIT_UNRN_DM_AMOUNT':
                    case 'PERMIT_NON_BANK_LIMIT_PAYEE':
                        $ret['errmsg'] = '收款账号需补充身份信息!';
                        break;
                    case 'PAYEE_NOT_EXIST':
                        $ret['errmsg'] = '收款账号不存在!';
                        break;
                    case 'PAYEE_USER_INFO_ERROR':
                        $ret['errmsg'] = '支付宝账号和姓名不匹配，请确认姓名是否正确!';
                        break;
                    case 'PAYER_BALANCE_NOT_ENOUGH':
                        $ret['errmsg'] = '付款方余额不足!';
                        break;
                    case 'PAYMENT_INFO_INCONSISTENCY':
                        $ret['errmsg'] = '两次请求商户单号一样，但是参数不一致!';
                        break;
                    case 'EXCEED_LIMIT_DM_MAX_AMOUNT':
                        $ret['errmsg'] = '单日最多可转100万元。!';
                        break;
                    default :
                        $ret['errmsg'] = '提现异常,请联系客服人员.错误码：' . $msg;
                        break;
                }*/
            }
            return $ret;
        } else {
            $ret['errcode'] = 1;
            $ret['errmsg'] = '支付宝连接失败';
            return $ret;
        }
    }


}